package org.agent.aigccore.basic.security;

import jakarta.annotation.Resource;
import org.agent.aigccore.core.service.user.UserService;
import org.agent.aigccore.model.po.UserInfoPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    
    @Resource
    private UserService userService;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("Loading user by username: {}", username);
        
        // 根据用户名查询用户信息
        UserInfoPO userInfoPO = userService.loadByUsername(username);
        
        if (userInfoPO == null) {
            logger.warn("User not found with username: {}", username);
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        logger.info("User found: {}, role: {}", username, userInfoPO.getRole());
        
        // 创建UserDetails对象
        return new User(
            userInfoPO.getUsername(),
            userInfoPO.getPassword(),
            Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + userInfoPO.getRole()))
        );
    }
}